import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: ScrollControllerWidget()));
}

class ScrollControllerWidget extends StatefulWidget {
  const ScrollControllerWidget({Key? key}) : super(key: key);

  @override
  _ScrollControllerWidgetState createState() => _ScrollControllerWidgetState();
}

class _ScrollControllerWidgetState extends State<ScrollControllerWidget> {
  ScrollController _controller = ScrollController();
  bool showTopBtn = false;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      print(_controller.offset); //  打印滚动位置
      if (_controller.offset < 1000 && showTopBtn) {
        setState(() => showTopBtn = false);
      } else if (_controller.offset > 1000 && showTopBtn == false) {
        setState(() => showTopBtn = true);
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("滚动控制"),
      ),
      body: Scrollbar(
        child: ListView.builder(
          itemCount: 100,
          itemExtent: 50.0,
          controller: _controller,
          itemBuilder: ((context, index) {
            return ListTile(
              title: Text("$index"),
            );
          }),
        ),
      ),
      floatingActionButton: !showTopBtn ? null : FloatingActionButton(
        child: const Icon(Icons.arrow_upward),
        onPressed: () {
          _controller.animateTo(
            .0, duration: const Duration(microseconds: 200),
            curve: Curves.easeInCirc
          );
        },
      ),
    );
  }
}
